package com.qiantu.phone.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.lifecycle.LifecycleOwner;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemDragListener;
import com.chad.library.adapter.base.module.BaseDraggableModule;
import com.chad.library.adapter.base.module.DraggableModule;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.hjq.base.BaseDialog;
import com.hjq.http.listener.HttpCallback;
import com.qiantu.api.db.HandleListener;
import com.qiantu.api.db.LLControllerDBManager;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.entity.ControllerBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.aop.Log;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.event.RefreshControllerEvent;
import com.qiantu.phone.event.RefreshDeviceListEvent;
import com.qiantu.phone.manager.ActivityManager;
import com.qiantu.phone.ui.dialog.ConfirmCancelHintDialog;
import com.rich.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.NotNull;

import java.io.Serializable;
import java.util.List;

import okhttp3.Call;

public class ControllerOrderActivity extends AppActivity {
    private int mPosition;
    private RecyclerView controlllerList;

    @Log
    public static void start(Context context, String controllerSerialNo, List<ControllerBean> controllerBeans) {
        Intent intent = new Intent(context, ControllerOrderActivity.class);
        intent.putExtra("controllerSerialNo", controllerSerialNo);
        intent.putExtra("controllerBeans", (Serializable) controllerBeans);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }
    @Override
    protected int getLayoutId() {
        return R.layout.activity_scene_order;
    }

    @Override
    protected void initView() {
        getTitleBar().setTitle(R.string.controller_sort);
        getTitleBar().setRightTitle(R.string.save);
        Gson gson = new Gson();
        List<ControllerBean> controllerBeans = (List<ControllerBean>) getIntent().getSerializableExtra("controllerBeans");
//        getTitleBar().getRightView().setEnabled(false);
        controlllerList = findViewById(R.id.scene_list);
        controlllerList.setLayoutManager(new LinearLayoutManager(getContext()));
        mAdapter = new ControllerOrderAdapter(controllerBeans);
        mAdapter.addChildClickViewIds(R.id.delete);
        mAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                int id = view.getId();
                if (id == R.id.delete) {
                    showConfirmCancelHintDialog(getString(R.string.delete_controller_hint_2), "取消", "删除", new ConfirmCancelHintDialog.OnListener() {
                        @Override
                        public void onLeftClick(BaseDialog dialog) {
                            dialog.dismiss();
                        }

                        @Override
                        public void onRightClick(BaseDialog dialog) {
                            ControllerBean controllerBean = mAdapter.getData().get(position);
                            LLHttpManager.controllerDelete((LifecycleOwner) getActivity(), controllerBean.getControllerSerialNo(), new HttpCallback<HttpData<Void>>(null){
                                @Override
                                public void onStart(Call call) {
                                    showDialog(getString(R.string.deleting));
                                }

                                @Override
                                public void onSucceed(HttpData<Void> result) {
                                    LLControllerDBManager.getInstance(getContext()).remove(controllerBean.getControllerSerialNo());
                                    mAdapter.removeAt(position);
                                    EventBus.getDefault().post(new RefreshControllerEvent());
                                    if(controllerBean != null){
                                        boolean isRemoved = LLDeviceDBManager.getInstance(getContext()).removeByControllerSerialNo(controllerBean.getControllerSerialNo());
                                        if(isRemoved){
                                            EventBus.getDefault().post(new RefreshDeviceListEvent());
                                        }
                                    }
                                    toast(R.string.delete_success);
                                }

                                @Override
                                public void onFail(Exception e) {
                                    super.onFail(e);
                                }

                                @Override
                                public void onEnd(Call call) {
                                    hideDialog();
                                }
                            });
                        }
                    });
                }
            }
        });
        mAdapter.getDraggableModule().setOnItemDragListener(new OnItemDragListener() {
            @Override
            public void onItemDragStart(RecyclerView.ViewHolder viewHolder, int i) {
                mPosition = i;
                viewHolder.itemView.setBackgroundResource(R.drawable.setting_item_selector_pressed);
            }

            @Override
            public void onItemDragMoving(RecyclerView.ViewHolder viewHolder, int i, RecyclerView.ViewHolder viewHolder1, int i1) {

            }

            @Override
            public void onItemDragEnd(RecyclerView.ViewHolder viewHolder, int i) {

                if (mPosition != i) {
//                    doSort();
                }
                viewHolder.itemView.setBackgroundResource(R.drawable.setting_item_pressed_bg);
            }
        });
        mAdapter.getDraggableModule().setDragEnabled(true);
        mAdapter.getDraggableModule().getItemTouchHelperCallback().setSwipeMoveFlags(ItemTouchHelper.START | ItemTouchHelper.END);
        controlllerList.setAdapter(mAdapter);
    }

    @Override
    protected void initData() {
    }

    private ControllerOrderAdapter mAdapter;

    private class ControllerOrderAdapter extends BaseQuickAdapter<ControllerBean, BaseViewHolder> implements DraggableModule {
        public ControllerOrderAdapter(List<ControllerBean> data) {
            super(R.layout.scene_order_ly, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, ControllerBean item) {
            helper.setText(R.id.name, item.getName());

        }

        @NotNull
        @Override
        public BaseDraggableModule addDraggableModule(@NotNull BaseQuickAdapter<?, ?> baseQuickAdapter) {
            return new BaseDraggableModule(baseQuickAdapter);
        }
    }

    @Override
    public void onRightClick(View view) {
        doSort();
    }

    private void doSort() {
        LLHttpManager.controllerSort(this, mAdapter.getData(), new HttpCallback<HttpData<Void>>(this) {
            @Override
            public void onSucceed(HttpData<Void> result) {
                super.onSucceed(result);
                for (ControllerBean controllerBean : mAdapter.getData()){
                    LLControllerDBManager.getInstance(getActivity()).put(controllerBean);
                }
                EventBus.getDefault().post(new RefreshControllerEvent());
                finish();
            }
            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }
        });
    }
}